package com.heima.article.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.AppThreadUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("userId");
        //判断是否为空  且不能是游客身份登录 不为空存入线程中
        if (!StringUtils.isEmpty(header) ){
            int userId = Integer.parseInt(header);
            User user = new User(userId);
            AppThreadUtil.setThread(user);
        }
        return true;
    }

    /*
        释放线程
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AppThreadUtil.delThread();
    }
}
